package com.smart.primary.util;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;


public class UploadUtil {


	/**
	 * 完结版
	 * @param file
	 * @param upPath    上传路径  /image/   后面加/
	 * @param filePath  true  相对路径   false  文件名
	 * @return
	 */
	public static String upLoad(MultipartFile file,HttpServletRequest request,String upPath, boolean timeName, boolean filePath) {
		upPath=upPath(upPath);
		//保存路径
		//String resURL = PropertiesUtil.getString("res.upload.url");
		String resURL = null;

		if(StringUtils.isBlank(resURL)){
			resURL = request.getSession().getServletContext().getRealPath("/");
		}

		File images=new File(resURL+upPath);

		//如果原文件名过长则截取后10位
		String fileName=file.getOriginalFilename();


		//文件后缀名
		String ext = FilenameUtils.getExtension(fileName);
		if(timeName){
			fileName =System.currentTimeMillis()+ new Random().nextInt(10000) + "." + ext;
		}
		//文件名 当前时间的毫秒值和原文件名拼接
		File targetFile = new File(images, fileName);
		//文件夹不存在则创建
		if(!images.exists()){
			images.mkdirs();
		}
		try {
			file.transferTo(targetFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(filePath){
			return resURL+upPath+fileName;
		}
		return fileName;
	}

	public static String upPath(String str){
		if(str.endsWith("/") || str.endsWith("\\")){
			return str;
		}
		return str+"/";
	}

}
